package com.atguigu.spzx.service.product.service.impl;

import com.atguigu.spzx.service.product.mapper.CategoryMapper;
import com.atguigu.spzx.service.product.service.CategoryService;
import com.atguigu.spzx.model.entity.category.Category;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * title:
 * author: zgl
 * date: 2024/1/15
 * description：
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {
    @Autowired
    private RedisTemplate redisTemplate;
 /*   @Override
    public List<Category> findCategoryTree() {
        Object cates = redisTemplate.opsForValue().get("spzx:redis:cates");
        if(cates != null){
            return (List<Category>) cates;
        }
            List<Category> categoryList = baseMapper.selectList(Wrappers.lambdaQuery(Category.class).eq(Category::getDeleted,0));
            List<Category> oneCategoryList = categoryList.stream().filter(category -> category.getParentId().equals(0L)).collect(Collectors.toList());
            buildCategoryTree(oneCategoryList,categoryList);
            redisTemplate.opsForValue().set("spzx:redis:cates",oneCategoryList,10, TimeUnit.MINUTES);
            return oneCategoryList;
    }*/


    @Cacheable(value = "spzx:cache",key = "'cates'")
    @Override
    public List<Category> findCategoryTree() {
        List<Category> categoryList = baseMapper.selectList(Wrappers.lambdaQuery(Category.class).eq(Category::getDeleted,0));
        List<Category> oneCategoryList = categoryList.stream().filter(category -> category.getParentId().equals(0L)).collect(Collectors.toList());
        buildCategoryTree(oneCategoryList,categoryList);
        return oneCategoryList;
    }

    private void buildCategoryTree(List<Category> oneCategoryList, List<Category> categoryList) {
        if(CollectionUtils.isEmpty(oneCategoryList)){
            return;
        }
        oneCategoryList.forEach(oneCategory->{
            List<Category> children = categoryList.stream().filter(twoCategory -> twoCategory.getParentId().equals(oneCategory.getId())).collect(Collectors.toList());
           if(!CollectionUtils.isEmpty(children)){
               oneCategory.setChildren(children);
               buildCategoryTree(children,categoryList);
           }
        });
    }
}
